import * as adminApi from '../../api/admin_manage'
import {
  SUCCESS_CODE,
  FETCH_ADMIN_LIST_FAILED,
  DEFAULT_ADMIN_PASSWORD,
  RESET_PASSWORD_SUCCESS
} from '../../config/config'

const UPDATE_ADMIN_LIST = 'UPDATE_ADMIN_LIST'
const adminManage = {
  namespaced: true,
  state: {
    adminList: [],
    search: {
      name: '',
      loginName: ''
    },
    adminEdit: {
      name: '',
      loginName: '',
      password: '',
      confirmPass: ''
    }
  },
  mutations: {
    [UPDATE_ADMIN_LIST](state, adminList) {
      state.adminList = adminList
    }
  },
  actions: {
    fetchAdminList({commit, state}) {
      return new Promise((resolve, reject) => {
        adminApi.fetchAdminList(state.search).then(data => {
          data = data.data
          if (data.status === SUCCESS_CODE) {
            commit(UPDATE_ADMIN_LIST, data.data)
            resolve(true)
          } else {
            reject(new Error(FETCH_ADMIN_LIST_FAILED))
          }
        })
      })
    },
    newAdmin({commit}, admin) {
      return new Promise((resolve, reject) => {
        adminApi.newAdmin(admin).then(data => {
          if (data.data.status === SUCCESS_CODE) {
            resolve()
          } else {
            reject(new Error(`添加失败 code: ${data.data.status}`))
          }
        })
      })
    },
    updateStatus({commit}, selectedAdmin) {
      let status = (selectedAdmin.status === 'ENABLE' ? 'DISABLE' : 'ENABLE')
      return new Promise((resolve, reject) => {
        adminApi.updateStatus(selectedAdmin.id, status).then(data => {
          if (data.data.status === SUCCESS_CODE) {
            alert('操作成功！')
            resolve()
          }
        })
      })
    },
    resetAdminPwd({commit}, id, pwd) {
      return new Promise((resolve, reject) => {
        adminApi.resetAdminPwd(id, DEFAULT_ADMIN_PASSWORD).then(data => {
          if (data.data.status === SUCCESS_CODE) {
            alert(RESET_PASSWORD_SUCCESS)
            resolve()
          } else {
            reject(new Error(`添加失败 code: ${data.data.status}`))
          }
        })
      })
    },
    updatePassword({commit}, updateObj) {
      return new Promise(resolve => {
        adminApi.updatePassword(updateObj).then(data => {
          resolve(data.data)
        })
      })
    },
    // 获取管理员绩效
    getAdminPerformance(searchObj) {
      return new Promise(resolve => {
        adminApi.getAdminPerformance(searchObj).then(data => {
          resolve(data.data)
        })
      })
    }
  }
}

export default adminManage
